package timer

import (
	"fmt"
	"github.com/Sir-yuChen/funAnalyse/global/constant"
	"strings"
	"time"
)

func CreateCronStr(intervalMap map[string]int64, startTime time.Time, b bool) string {
	//校验是否有周期 b
	cronStr := ""
	cronMap := map[string]string{} //存入顺序 秒 分钟 小时 日 月 周 年份
	// 30 10 1 20 10 ? 2011 2011年10月20号1点10分30秒触发任务
	keys := []string{
		//constant.Interval_Unit_Second, corn v3 分，时，日，月，星期
		constant.Interval_Unit_Minute,
		constant.Interval_Unit_Hour,
		constant.Interval_Unit_Day,
		constant.Interval_Unit_Month,
		constant.Interval_Unit_Week,
		//constant.Interval_Unit_Year,
	}

	cronMap[constant.Interval_Unit_Second] = fmt.Sprint(startTime.Second())
	cronMap[constant.Interval_Unit_Minute] = fmt.Sprint(startTime.Minute())
	cronMap[constant.Interval_Unit_Hour] = fmt.Sprint(startTime.Hour())
	cronMap[constant.Interval_Unit_Day] = fmt.Sprint(startTime.Day())
	cronMap[constant.Interval_Unit_Month] = fmt.Sprint(int(startTime.Month()))
	cronMap[constant.Interval_Unit_Week] = "?"
	//cronMap[constant.Interval_Unit_Year] = fmt.Sprint(startTime.Year()) //1970-2099

	cronList := make([]string, 0, len(cronMap))
	if b {
		//处理有周期的
		index := 0
		for i, v := range keys {
			vm, ok := intervalMap[v]
			if ok {
				index = i
				if ok {
					cronList = append(cronList, "0"+"/"+fmt.Sprint(vm))
				}
			} else {
				if i > index {
					if v == constant.Interval_Unit_Week {
						cronList = append(cronList, "?")
					} else {
						cronList = append(cronList, "*")
					}
				} else {
					bo, ok := cronMap[v]
					if ok {
						cronList = append(cronList, bo)
					}
				}
			}

		}
	} else {
		for _, v := range keys {
			mv, ok := cronMap[v]
			if ok {
				cronList = append(cronList, mv)
			}
		}
	}
	cronStr = strings.Join(cronList, " ")
	return cronStr
}
